﻿using System;
using System.Linq;
using TeamLemonApp.Models;

namespace TeamLemonApp.DataPersisters
{
    public class UserDataPersister
    {

        private const int MinUsernameLength = 6;
        private const int MaxUsernameLength = 30;
        private const string ValidUsernameCharacters =
            "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890_.";

        private const int AuthCodeLength = 40;

        private const string BaseServicesUrl = "http://arialwebapirecipe.apphb.com/api/";

        internal static void RegisterUser(string username, string nickname, string authenticationCode)
        {
            ValidateUsername(username);
            ValidateAuthCode(authenticationCode);

            var userModel = new UserModel()
            {
                Username = username,
                Nickname = nickname,
                Password = authenticationCode,
            };

            HttpRequester.Post(BaseServicesUrl + "users/register",
                userModel);
        }

        internal static LoginResponseModel LoginUser(string username, string authenticationCode)
        {
            var userModel = new UserModel()
            {
                Username = username,
                Password = authenticationCode
            };

            var loginResponse = HttpRequester.Post<LoginResponseModel>(BaseServicesUrl + "users/login",
                userModel);


            return loginResponse;
        }

        internal static void LogoutUser(string sessionKey)
        {
            HttpRequester.Get(BaseServicesUrl + "users/logout/" + sessionKey);
        }

        private static void ValidateAuthCode(string authCode)
        {
            if (authCode == null)
            {
                throw new ArgumentNullException("Password cannot be null");
            }

            if (authCode.Length != AuthCodeLength)
            {
                throw new ArgumentOutOfRangeException("Password should be encrypted");
            }
        }

        private static void ValidateUsername(string username)
        {

            if (username == null)
            {
                throw new ArgumentNullException("Username cannot be null");
            }

            if (username.Length < MinUsernameLength
                || username.Length > MaxUsernameLength)
            {
                throw new ArgumentOutOfRangeException(
                   string.Format("Username must be between {0} and {1} characters long",
                   MinUsernameLength, MaxUsernameLength));
            }

            if (username.Any(ch => !ValidUsernameCharacters.Contains(ch)))
            {
                throw new ArgumentOutOfRangeException(
                    "Username must contain only Latin letters, digits '.','_'");
            }
        }
    }
}